@file:Suppress("unused")

package xyz.scootaloo.kami.cloud.model

import io.vertx.core.json.JsonObject
import io.vertx.kotlin.core.json.Json
import io.vertx.kotlin.core.json.obj
import org.ktorm.database.Database
import org.ktorm.entity.Entity
import org.ktorm.entity.sequenceOf
import org.ktorm.schema.Table
import org.ktorm.schema.int
import org.ktorm.schema.long
import org.ktorm.schema.varchar
import xyz.scootaloo.kami.cloud.lang.JsonSerializable
import xyz.scootaloo.kami.cloud.lang.JsonSerializer
import xyz.scootaloo.kami.cloud.lang.currentTimeMillis
import xyz.scootaloo.kami.cloud.lang.set
import kotlin.reflect.KClass

/**
 * @author flutterdash@qq.com
 * @since 2022/4/10 21:31
 */

interface EntityUser : Entity<EntityUser>, JsonSerializable {
    var id: Int
    var username: String
    var password: String
    var role: Int
    var created: Long

    companion object : Entity.Factory<EntityUser>() {
        fun create(username: String, password: String, role: Int) = EntityUser {
            this.username = username
            this.password = password
            this.role = role
            this.created = currentTimeMillis()
        }
    }
}

object EntityUsers : Table<EntityUser>("users") {
    val id = int("id").primaryKey().bindTo { it.id }
    val username = varchar("username").bindTo { it.username }
    val password = varchar("password").bindTo { it.password }
    val role = int("role").bindTo { it.role }
    val created = long("created").bindTo { it.created }
}

object EntityUserSerializer : JsonSerializer<EntityUser> {
    override fun accept(): KClass<EntityUser> {
        return EntityUser::class
    }

    override fun deserialize(json: JsonObject): EntityUser {
        return EntityUser {
            id = json.getInteger("id")
            username = json.getString("username")
            password = json.getString("password")
            role = json.getInteger("role")
            created = json.getLong("created")
        }
    }

    override fun serialize(any: EntityUser): JsonObject {
        return Json.obj {
            this["id"] = any.id
            this["username"] = any.username
            this["password"] = any.password
            this["role"] = any.role
            this["created"] = any.created
        }
    }
}

val Database.users get() = this.sequenceOf(EntityUsers)